<script setup lang="tsx">
import { nextTick, reactive, ref, watch } from 'vue';
import { NCheckbox, NCheckboxGroup, NSpace } from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';
import { fetchGetRoleMenu } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { AddRoleMenuArry, AddRolePermArry, RemoveRoleMenuArry, RemoveRolePermArry } from './shared';
defineOptions({
  name: 'RoleMenu'
});
interface RowData {
  name: string;
  id: number;
  children?: RowData[];
  permission: PermissionObject[];
}
interface PermissionObject {
  code: string;
  name: string;
}

interface Props {
  roleId: number;
}

const props = defineProps<Props>();
const appStore = useAppStore();
const screenHeight = document.documentElement.clientHeight || window.innerHeight;
const tableHeight = screenHeight - 330;
const roleData: RowData[] = reactive([]);
const menuId = ref<number[]>([]);
const permCode = ref<string[]>([]);
const chkpermCode = ref<string[]>([]);
async function GetData(roleId: number) {
  const { data, error } = await fetchGetRoleMenu();
  if (!error) {
    Object.assign(roleData, data);
    menuId.value = [];
    permCode.value = [];
    // checkedKeys.value = ['sys:user:add', 'sys:job:add'];
    menuId.value.push(roleId);
    if (roleId === 1300000000102) {
      permCode.value.push('sys:user:add', 'sys:job:add');
      chkpermCode.value.push('sys:user:add');
    } else {
      permCode.value.push('sys:user:edit');
      chkpermCode.value.push('sys:user:edit');
    }
  }
}

const columns: DataTableColumns<RowData> = [
  {
    type: 'selection'
  },
  {
    title: '菜单',
    key: 'name',
    align: 'left',
    width: 300
  },
  {
    key: 'id',
    title: '权限',
    align: 'left',
    render: row => {
      return (
        <div class="flex">
          <NCheckboxGroup default-Value={chkpermCode.value} on-update:value={getPermission}>
            <NSpace>
              {row.permission &&
                row.permission.map(item => <NCheckbox value={item.code} label={item.name}></NCheckbox>)}
            </NSpace>
          </NCheckboxGroup>
        </div>
      );
    }
  }
];
function getPermission(_: string[], meta: { actionType: 'check' | 'uncheck'; value: string }) {
  if (meta.actionType === 'check') {
    permCode.value.push(meta.value);
  } else {
    permCode.value = permCode.value?.filter(a => a !== meta.value);
  }
}

function rowKey(row: RowData) {
  return row.id;
}
// 查找指定菜单
function findItem(id: number, data: RowData[]): RowData | null {
  for (const item of data) {
    if (item.id === id) return item;
    if (item.children?.length) {
      const found = findItem(id, item.children);
      if (found) return found;
    }
  }
  return null;
}
function recursCode(data: RowData) {
  menuId.value = AddRoleMenuArry(menuId.value, data.id);
  if (data.permission?.length) {
    data.permission.forEach(a => {
      permCode.value = AddRolePermArry(permCode.value, a.code);
    });
  }
  if (data.children?.length) {
    for (const item of data.children) {
      recursCode(item);
    }
  }
}
function recursCodeRemove(data: RowData) {
  menuId.value = RemoveRoleMenuArry(menuId.value, data.id);
  if (data.permission?.length) {
    data.permission.forEach(a => {
      permCode.value = RemoveRolePermArry(permCode.value, a.code);
    });
  }
  if (data.children?.length) {
    for (const item of data.children) {
      recursCode(item);
    }
  }
}
function selectkeys(
  _keys: (string | number)[],
  _rows: object[],
  meta: { row: object | undefined; action: 'check' | 'uncheck' | 'checkAll' | 'uncheckAll' }
) {
  if (meta.action === 'check') {
    const drow = meta.row as RowData;
    recursCode(drow);
  } else if (meta.action === 'uncheck') {
    const drow = meta.row as RowData;
    recursCodeRemove(drow);
  } else if (meta.action === 'checkAll') {
    console.log('checkAll');
  } else if (meta.action === 'uncheckAll') {
    console.log('uncheckAll');
  }
}

// 监听 roleId 的变化
watch(
  () => props.roleId,
  async (newRoleId: number) => {
    if (newRoleId) {
      console.log(newRoleId);
      await GetData(newRoleId);
    }
  },
  { immediate: true }
);
function savePermission() {
  // 授权菜单
  console.log(menuId.value);
  // 授权按钮
  console.log(permCode.value);
  window.$message?.success('授权成功');
}
</script>

<template>
  <div class="flex-col-stretch gap-16px">
    <NSpace>
      <NButton ghost type="primary" size="small" @click="savePermission">授权功能</NButton>
    </NSpace>
    <NFlex class="h-full">
      <NDataTable
        v-model:checked-row-keys="menuId"
        :columns="columns"
        :cascade="false"
        :data="roleData"
        :row-key="rowKey"
        children-key="children"
        :style="{ height: `${tableHeight}px` }"
        :flex-height="!appStore.isMobile"
        @update-checked-row-keys="selectkeys"
      />
    </NFlex>
  </div>
</template>

<style scoped></style>
